<template>
  <!-- 主界面 -->
  <div v-if="!gameStarted" class="main-menu">
    <h1>贪吃蛇大冒险</h1>
    <button @click="startGame" class="menu-btn">开始游戏</button>
    <div class="menu-options">
      <div class="option-group">
        <h3>难度选择</h3>
        <select v-model="difficulty">
          <option value="easy">简单</option>
          <option value="medium">中等</option>
          <option value="hard">困难</option>
        </select>
      </div>
      <div class="option-group">
        <h3>皮肤选择</h3>
        <div class="skin-options">
          <button
            v-for="skin in skins"
            :key="skin.id"
            @click="currentSkin = skin.id"
            :class="{ active: currentSkin === skin.id }"
            :style="skin.previewStyle"
          ></button>
        </div>
      </div>
    </div>
    <button @click="showRanking = true" class="menu-btn">排行榜</button>
  </div>

  <!-- 游戏界面 -->
  <div v-else class="game-container">
    <!-- 游戏控制栏 -->
    <div class="game-header">
      <div class="game-info">
        得分: {{ score }} | 长度: {{ snake.length }} | 难度: {{ difficultyText }}
      </div>
      <div class="game-controls">
        <button @click="togglePause" class="control-btn">
          {{ isPaused ? '继续' : '暂停' }}
        </button>
        <button @click="endGame" class="control-btn">结束</button>
      </div>
    </div>

    <!-- 游戏棋盘 -->
    <div class="game-board" :style="boardStyle">
      <!-- 蛇身 -->
      <div
        v-for="(segment, index) in snake"
        :key="index"
        class="snake-segment"
        :class="currentSkin"
        :style="getSegmentStyle(segment)"
      ></div>

      <!-- 食物 -->
      <div
        class="food"
        :style="{
          ...foodPosition,
          animation: `foodSpawn 0.3s ease-out ${foodSpawnTime}ms`
        }"
      >{{ currentFoodIcon }}</div>
    </div>

    <!-- 方向控制 -->
    <div class="direction-controls">
      <button @click="changeDirection('up')" class="dir-btn up">↑</button>
      <div class="dir-row">
        <button @click="changeDirection('left')" class="dir-btn left">←</button>
        <button @click="changeDirection('right')" class="dir-btn right">→</button>
      </div>
      <button @click="changeDirection('down')" class="dir-btn down">↓</button>
    </div>
  </div>

  <!-- 排行榜弹窗 -->
  <div v-if="showRanking" class="modal-overlay">
    <div class="ranking-modal">
      <h2>排行榜</h2>
      <div v-if="ranking.length > 0" class="ranking-list">
        <div v-for="(record, index) in ranking" :key="index" class="rank-item">
          <span class="rank">{{ index + 1 }}.</span>
          <span class="score">{{ record.score }}分</span>
          <span class="date">{{ record.date }}</span>
        </div>
      </div>
      <div v-else class="no-records">暂无记录</div>
      <button @click="showRanking = false" class="close-btn">关闭</button>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'

export default {
  setup() {
    // 游戏状态
    const gameStarted = ref(false)
    const isPaused = ref(false)
    const showRanking = ref(false)
    const foodSpawnTime = ref(0)

    // 游戏配置
    const difficulty = ref('medium')
    const difficultyText = computed(() => {
      return {
        easy: '简单',
        medium: '中等',
        hard: '困难'
      }[difficulty.value]
    })

    // 皮肤配置
    const skins = [
      { 
        id: 'classic',
        name: '经典绿',
        previewStyle: { background: '#4CAF50' }
      },
      {
        id: 'fire',
        name: '火焰',
        previewStyle: { 
          background: 'linear-gradient(45deg, #ff6b6b, #ffa502)'
        }
      },
      {
        id: 'rainbow',
        name: '彩虹',
        previewStyle: {
          background: 'linear-gradient(45deg, #ff6b6b, #ffa502, #4CAF50, #2196F3)'
        }
      }
    ]
    const currentSkin = ref('classic')

    // 食物配置
    const foodTypes = [
      { type: 'normal', icon: '🍎', color: '#ff4757' },
      { type: 'speed', icon: '⚡', color: '#f9ca24' },
      { type: 'life', icon: '❤️', color: '#ff7675' }
    ]
    const currentFoodIcon = computed(() => {
      const foodType = foodTypes.find(ft => ft.type === food.type)
      return foodType ? foodType.icon : '🍎'
    })

    // 游戏数据
    const gridSize = ref(20)
    const snake = reactive([{ x: 10, y: 10 }])
    const food = reactive({ x: 15, y: 15, type: 'normal' })
    const direction = ref('right')
    const score = ref(0)
    const gameLoop = ref(null)
    const ranking = ref(JSON.parse(localStorage.getItem('snakeRanking') || '[]'))

    // 计算属性
    const baseSpeed = computed(() => ({
      easy: 300,
      medium: 200,
      hard: 100
    }[difficulty.value]))

    const boardStyle = computed(() => ({
      width: `${gridSize.value * 20}px`,
      height: `${gridSize.value * 20}px`
    }))

    const foodPosition = computed(() => ({
      left: `${food.x * 20}px`,
      top: `${food.y * 20}px`
    }))

    // 游戏方法
    const spawnFood = () => {
      do {
        food.x = Math.floor(Math.random() * gridSize.value)
        food.y = Math.floor(Math.random() * gridSize.value)
        food.type = foodTypes[Math.floor(Math.random() * foodTypes.length)].type
        foodSpawnTime.value = Date.now() % 1000
      } while (snake.some(s => s.x === food.x && s.y === food.y))
    }

    const checkCollision = (pos) => {
      return pos.x < 0 || pos.x >= gridSize.value ||
             pos.y < 0 || pos.y >= gridSize.value ||
             snake.some(s => s.x === pos.x && s.y === pos.y)
    }

    const saveRecord = () => {
      ranking.value.push({
        score: score.value,
        date: new Date().toLocaleString(),
        difficulty: difficulty.value
      })
      ranking.value.sort((a, b) => b.score - a.score)
      localStorage.setItem('snakeRanking', JSON.stringify(ranking.value.slice(0, 10)))
    }

    const move = () => {
      if (isPaused.value) return

      const head = { ...snake[0] }
      switch(direction.value) {
        case 'up': head.y--; break
        case 'down': head.y++; break
        case 'left': head.x--; break
        case 'right': head.x++; break
      }

      if (checkCollision(head)) {
        endGame()
        return
      }

      if (head.x === food.x && head.y === food.y) {
        score.value += 10
        spawnFood()
      } else {
        snake.pop()
      }

      snake.unshift(head)
    }

    const startGame = () => {
      gameStarted.value = true
      isPaused.value = false
      snake.splice(0, snake.length, { x: 10, y: 10 })
      direction.value = 'right'
      score.value = 0
      spawnFood()
      gameLoop.value = setInterval(move, baseSpeed.value)
    }

    const endGame = () => {
      clearInterval(gameLoop.value)
      saveRecord()
      alert(`游戏结束！得分: ${score.value}`)
      gameStarted.value = false
    }

    const togglePause = () => {
      isPaused.value = !isPaused.value
    }

    const changeDirection = (newDir) => {
      if (isPaused.value) return
      
      const opposite = { up: 'down', down: 'up', left: 'right', right: 'left' }
      if (newDir !== opposite[direction.value]) {
        direction.value = newDir
      }
    }

    const getSegmentStyle = (segment) => {
      const baseStyle = {
        left: `${segment.x * 20}px`,
        top: `${segment.y * 20}px`,
        width: '18px',
        height: '18px',
        transition: 'all 0.15s ease-out'
      }

      if (currentSkin.value === 'rainbow') {
        const hue = (segment.x * 10 + segment.y * 10) % 360
        baseStyle.background = `hsl(${hue}, 70%, 50%)`
      }

      return baseStyle
    }

    // 键盘控制
    onMounted(() => {
      window.addEventListener('keydown', (e) => {
        if (e.key === ' ') togglePause()
        
        const dirMap = {
          ArrowUp: 'up',
          ArrowDown: 'down',
          ArrowLeft: 'left',
          ArrowRight: 'right'
        }
        if (dirMap[e.key]) changeDirection(dirMap[e.key])
      })
    })

    onBeforeUnmount(() => {
      clearInterval(gameLoop.value)
    })

    return {
      // 状态
      gameStarted,
      isPaused,
      showRanking,
      difficulty,
      difficultyText,
      currentSkin,
      score,
      snake,
      ranking,
      
      // 计算属性
      boardStyle,
      foodPosition,
      currentFoodIcon,
      
      // 方法
      startGame,
      endGame,
      togglePause,
      changeDirection,
      getSegmentStyle,
      
      // 配置
      skins,
      foodTypes
    }
  }
}
</script>

<style scoped>
/* 主菜单样式 */
.main-menu {
  max-width: 500px;
  margin: 50px auto;
  padding: 30px;
  text-align: center;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
  color: white;
}

.main-menu h1 {
  font-size: 2.5rem;
  margin-bottom: 30px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}

.menu-btn {
  display: block;
  width: 80%;
  max-width: 300px;
  margin: 15px auto;
  padding: 12px;
  font-size: 1.2rem;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-btn:hover {
  background: #45a049;
  transform: translateY(-2px);
}

.menu-options {
  margin: 30px 0;
  padding: 20px;
  background: rgba(255,255,255,0.1);
  border-radius: 10px;
}

.option-group {
  margin-bottom: 20px;
}

.option-group h3 {
  margin-bottom: 10px;
}

.skin-options {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 10px;
}

.skin-options button {
  width: 40px;
  height: 40px;
  border: 2px solid transparent;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.skin-options button.active {
  border-color: white;
  transform: scale(1.1);
}

/* 游戏界面样式 */
.game-container {
  max-width: 500px;
  margin: 20px auto;
  padding: 20px;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
  color: white;
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  background: rgba(255,255,255,0.1);
  border-radius: 8px;
}

.game-controls {
  display: flex;
  gap: 10px;
}

.control-btn {
  padding: 8px 15px;
  background: rgba(255,255,255,0.9);
  color: #1e3c72;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.2s;
}

.control-btn:hover {
  background: white;
}

.game-board {
  position: relative;
  margin: 0 auto;
  background: rgba(0,0,0,0.3);
  border-radius: 10px;
  overflow: hidden;
}

.snake-segment {
  position: absolute;
  border-radius: 4px;
}

.classic {
  background: #4CAF50;
}

.fire {
  background: linear-gradient(45deg, #ff6b6b, #ffa502);
}

.food {
  position: absolute;
  font-size: 20px;
  animation: foodSpawn 0.3s ease-out;
}

@keyframes foodSpawn {
  from { transform: scale(0); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}

.direction-controls {
  margin-top: 20px;
  display: grid;
  grid-template-areas:
    ". up ."
    "left . right"
    ". down .";
  gap: 10px;
  justify-content: center;
}

.dir-btn {
  width: 60px;
  height: 60px;
  font-size: 24px;
  background: rgba(255,255,255,0.9);
  color: #1e3c72;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.2s;
}

.dir-btn:active {
  transform: scale(0.95);
}

.up { grid-area: up; }
.down { grid-area: down; }
.left { grid-area: left; }
.right { grid-area: right; }

/* 排行榜弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.ranking-modal {
  background: white;
  padding: 25px;
  border-radius: 10px;
  max-width: 90%;
  width: 400px;
  max-height: 80vh;
  overflow-y: auto;
  color: #333;
}

.ranking-modal h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #1e3c72;
}

.ranking-list {
  margin-bottom: 20px;
}

.rank-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.rank {
  font-weight: bold;
  color: #1e3c72;
}

.no-records {
  text-align: center;
  padding: 20px;
  color: #666;
}

.close-btn {
  display: block;
  width: 100%;
  padding: 10px;
  background: #1e3c72;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background 0.3s;
}

.close-btn:hover {
  background: #2a5298;
}
</style>